package com.gongpingjialoan.activity.car;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.TopBrandData;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.network.NetDataJson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.common.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/10/19.
 */
public class BrandTopFragment extends BaseScrollFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, NetDataJson.OnNetDataJsonListener {

    private View view;

    private PullToRefreshListView pullToRefreshListView;

    private ListView mListView;

    private NetDataJson netWork;

    private MyAdapter myAdapter;

    private List<TopBrandData> listData;

    private RelativeLayout fristLoading;

    private TextView titleTextView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        action = getArguments().getString("actions", "");
        isMainPage = true;
        view = inflater.inflate(R.layout.brand_fragment, container, false);
        fristLoading = (RelativeLayout) view.findViewById(R.id.main_loading);
        myAdapter = new MyAdapter();
        listData = new ArrayList<TopBrandData>();
        netWork = new NetDataJson(this);
        titleTextView = (TextView) view.findViewById(R.id.title);
        titleTextView.setText("品牌");
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        mListView = pullToRefreshListView.getRefreshableView();
        mListView.setOnItemClickListener(this);
        mListView.setAdapter(myAdapter);
        initData();
        return view;
    }



    // 控件初始化
    public void initData() {
        netWork.addParam("type", "brand");
        netWork.setUrl(API.hotbrandList);
        netWork.request("get");
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d("Brand", "onDestroyView");
        if (netWork != null) {
            netWork.cancelTask();
            netWork = null;
        }
        if (pullToRefreshListView != null) {
            if (pullToRefreshListView.isRefreshing()) {
                pullToRefreshListView.onRefreshComplete();
            }
        }
    }

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        String label =
                "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        initData();
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        fristLoading.setVisibility(View.GONE);
        pullToRefreshListView.onRefreshComplete();
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        fristLoading.setVisibility(View.GONE);
        pullToRefreshListView.onRefreshComplete();
        try {
            String update_time = json.getString("update_time");

            JSONArray jsonArray = json.getJSONArray("brand");
            if (jsonArray.length() > 0) {
                listData.clear();
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                TopBrandData data = new TopBrandData();
                data.logo_img = jsonArray.getJSONObject(i).getString("logo_img");
                data.name = jsonArray.getJSONObject(i).getString("name");
                data.score = jsonArray.getJSONObject(i).getString("score");
                data.slug = jsonArray.getJSONObject(i).getString("brand");
                listData.add(data);
            }
            myAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            Toast.makeText(getActivity(), "数据异常，请检查网络连接或稍后重试。", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), RankCarActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("brandSlug", listData.get(position - 1).slug);
        bundle.putBoolean("isBrand" , true);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    // 适配器
    public class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int arg0) {
            return listData.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int pos, View arg1, ViewGroup arg2) {
            ViewHolder viewHolder = null;

            if (arg1 == null) {

                viewHolder = new ViewHolder();
                LayoutInflater mInflater = LayoutInflater.from(getActivity());
                arg1 = mInflater.inflate(R.layout.item_brand_top, null);

                viewHolder.car_brand = (TextView) arg1.findViewById(R.id.car_brand);
                viewHolder.car_index = (TextView) arg1.findViewById(R.id.car_index);
                viewHolder.car_score = (TextView) arg1.findViewById(R.id.car_score);
                viewHolder.brandLogo = (ImageView) arg1.findViewById(R.id.brandLogo);
                viewHolder.mImageView = (ImageView) arg1.findViewById(R.id.image);
                arg1.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) arg1.getTag();
            }

            viewHolder.car_brand.setText(listData.get(pos).name);
            viewHolder.car_score.setText(listData.get(pos).score);




            ImageLoad.LoadImage(viewHolder.brandLogo, listData.get(pos).logo_img, R.drawable.brandnull, R.drawable.brandnull,getActivity());
            //  Glide.with(BrandTopFragment.this).load(listData.get(pos).logo_img).placeholder(R.drawable.brandnull).error(R.drawable.brandnull).into(viewHolder.brandLogo);

            if (pos == 0) {
                viewHolder.car_index.setVisibility(View.GONE);
                viewHolder.mImageView.setVisibility(View.VISIBLE);
                viewHolder.mImageView.setImageResource(R.drawable.jin);
            } else if (pos == 1) {
                viewHolder.car_index.setVisibility(View.GONE);
                viewHolder.mImageView.setVisibility(View.VISIBLE);
                viewHolder.mImageView.setImageResource(R.drawable.yin);
            } else if (pos == 2) {
                viewHolder.car_index.setVisibility(View.GONE);
                viewHolder.mImageView.setVisibility(View.VISIBLE);
                viewHolder.mImageView.setImageResource(R.drawable.tong);
            } else {
                viewHolder.car_index.setVisibility(View.VISIBLE);
                viewHolder.mImageView.setVisibility(View.GONE);
                viewHolder.car_index.setText(pos + 1 + "");
            }

            return arg1;
        }

        class ViewHolder {
            TextView car_brand;

            TextView car_index;

            TextView car_score;

            ImageView mImageView;

            ImageView brandLogo;

        }

    }
}
